package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.jdbc.datasource.IsolationLevelDataSourceAdapter;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;
import static com.hmdp.utils.SystemConstants.USER_NICK_NAME_PREFIX;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 小旭
 * @since 2021-12-22
 */
@Service
@Slf4j
public  class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private RedisTemplate stringRedisTemplate;

    /**
     * 发送验证码
     * @param phone
     * @param session
     * @return
     */
    @Override
    public Result sendCode(String phone, HttpSession session) {
        //1.判断手机号码格式
        boolean phoneInvalid = RegexUtils.isPhoneInvalid(phone);
        if (phoneInvalid) {
            return Result.fail("手机格式有误");
        }
        //1.1将手机号码存入session中
        session.setAttribute("phone", phone);
        //2.生成验证码
        String code = RandomUtil.randomNumbers(6);
       /* //3.将验证码存入session
        session.setAttribute("code",code);*/
        //3.将验证码存入redis
        stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY + phone, code, LOGIN_CODE_TTL, TimeUnit.MINUTES);
        //4.发送验证码
        log.info("发送短信验证码成功，验证码为{}", code);
        return Result.ok();
    }

    /**
     * 短息登录
     * @param loginForm
     * @param session
     * @return
     */
    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        //1.验证手机号码与之前的是否一致
       /* String phoneNum = (String) session.getAttribute("phone");
        if (!phoneNum.equals(loginForm.getPhone())) {
            return Result.fail("手机号不一致");
        }*/
       /* //2.验证验证码与之前是否一致
        String codeNum = (String) session.getAttribute("code");
        if (loginForm.getCode() == null || !codeNum.equals(loginForm.getCode())) {
            return Result.fail("验证码有误");
        }*/
        //2.从redis中获取验证码
        String codeNum = (String) stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY + loginForm.getPhone());
        if (loginForm.getCode() == null || !codeNum.equals(loginForm.getCode())) {
            return Result.fail("验证码有误");
        }
        //3.查询数据库该用户是否存在
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getPhone, loginForm.getPhone());
        User user = this.getOne(lambdaQueryWrapper);
        //4.如果不存在，则注册为新用户
        if (user == null) {
            user = createUserWithPhone(loginForm);
        }
        /*//5.将user保存到session中
        session.setAttribute("user", user);*/
        //保存用户信息到redis中
        //7.1随机生成token，作为登录令牌
        String token = UUID.randomUUID().toString(true);
        //7.2将user对象转为HashMap存储
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
//        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO);
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO, new HashMap<>(),
                CopyOptions.create()
                        .setIgnoreNullValue(true)
                        .setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));
        //7.3存储
        String tokenKey = LOGIN_USER_KEY + token;
        stringRedisTemplate.opsForHash().putAll(tokenKey, userMap);

        //7.4设置token有效期
        stringRedisTemplate.expire(tokenKey, LOGIN_USER_TTL, TimeUnit.MINUTES);
        //8.返回token
        return Result.ok(token);
    }


    /**
     * 获取用户信息
     * @param userId
     * @return
     */
    @Override
    public Result getUserById(Long userId) {
        User user = this.getById(userId);
        if (user == null) {
            return Result.fail("用户不存在");
        } else {
            UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
            return Result.ok(userDTO);
        }
    }

    /**
     * 用户签到
     * @return
     */
    @Override
    public Result toSign() {
        //获取用户信息
        Long userId = UserHolder.getUser().getId();
        //获取当前时间
        LocalDateTime now = LocalDateTime.now();
        //拼接key
        String keySuffix = now.format(DateTimeFormatter.ofPattern(":yyyy-MM"));
        String key = USER_SIGN_KEY + userId + keySuffix;
        //获取今天是本月第几天
        int dayOfMonth = now.getDayOfMonth();
        //写入Redis setbit key offset 1
        stringRedisTemplate.opsForValue().setBit(key, dayOfMonth - 1, true);
        log.info("添加成功");
        return Result.ok();
    }

    /**
     * 签到统计
     * @return
     */
    @Override
    public Result signCount() {
        //获取用户信息
        Long userId = UserHolder.getUser().getId();
        //获取当前时间
        LocalDateTime now = LocalDateTime.now();
        //拼接key
        String keySuffix = now.format(DateTimeFormatter.ofPattern(":yyyy-MM"));
        String key = USER_SIGN_KEY + userId + keySuffix;
        //获取今天是本月第几天
        int dayOfMonth = now.getDayOfMonth();
        //获取本月截至到今天的所有签到记录，返回的是一个十进制数字 bitfield key [get|set|incr] u16 0
        List<Long> results = stringRedisTemplate.opsForValue().bitField(
                key,
                BitFieldSubCommands.create()
                        .get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth)).valueAt(0)
        );

        if (results == null || results.isEmpty()) {
            //没有签到结果
            return Result.ok(0);
        }
        //由于bitfield可以同时执行get、set、incr方法，因此results集合中可能不止一个
        //但是咱们只使用了get方法，因此results中只有一个元素
        Long num = results.get(0);

        if (num == null || num == 0) {
            return Result.ok(0);
        }
        //循环遍历
        int count = 0;
        while ((num & 1) != 0) {
            count++;
            //将num向右移一位
            num = num >> 1;
        }

        return Result.ok(count);
    }

    /**
     * 登录时自动注册用户
     * @param loginForm
     * @return
     */
    private User createUserWithPhone(LoginFormDTO loginForm) {
        User user = new User();
        user.setPhone(loginForm.getPhone());
        user.setNickName(USER_NICK_NAME_PREFIX + RandomUtil.randomString(6));
        this.save(user);
        return user;
    }
}
